package com.my.context;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能:内容请求过滤器
 *
 * @author chenjun
 * @date 2016-6-28
 */
public class RequestFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private static String CONTEXT_PATH;
	private static String DEFAULT_PAGE;

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;


		// Referer检测
		/*String referer = request.getHeader("Referer");
		if (referer == null)
			referer = "";*/

		String url = request.getRequestURI();
		if (Pattern.compile(CONTEXT_PATH + "/?$").matcher(url).find()) { // 默认页  ||(!url.endsWith(DEFAULT_PAGE)&&referer==null)
			response.sendRedirect(CONTEXT_PATH + DEFAULT_PAGE);
		} else {
			arg2.doFilter(request, response); // 正常内容请求
		}
	}

	public void init(FilterConfig cfg) throws ServletException {
		ServletContext sc = cfg.getServletContext();
		CONTEXT_PATH = sc.getContextPath();
		DEFAULT_PAGE = sc.getInitParameter("defaultPage");
	}
}
